package com.micro.service.auth.server.login.validateCode;

import com.micro.service.common.utils.ValidateCodeUtil;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author lvxiucai
 * @description
 * @date 2019/7/20
 */
@RestController
public class ValidateCodeController {

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    public static final String SESSION_KEY_PREFIX = "SESSION_KEY_CODE_";

    @GetMapping("/code/image")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = ValidateCodeUtil.getCheckCode();//4位随机数
        BufferedImage image = ValidateCodeUtil.getPic(code);//图片
        ImageCode imageCode = new ImageCode(image,code,60);
        sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY_PREFIX+"IMAGE",imageCode);//把imageCode的code存到session里
        //可以通过流的形式写出去，也可以返回Base64转码后的字符串
        ImageIO.write(image,"JPEG",response.getOutputStream());

    }


}
